package com.jxud.controller;

import com.jxud.Pojo.*;
import com.jxud.service.ProductService;
import com.jxud.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@CrossOrigin(origins = "*")
public class ProductController {

    @Autowired
    private ProductService productService;

    /**
     * 商品查询
     *
     * @param pageProduct
     * @return
     */
    @PostMapping("/api/products")
    public Result getProducts(@RequestBody PageProduct pageProduct, HttpServletRequest request) {
        log.info("========================================查询商品=================================================");
        Map<String, Object> products = productService.getProducts(pageProduct, request);
        return Result.success(products);
    }

    /**
     * 创建商品
     *
     * @param product
     * @return
     */
    @PostMapping("/api/createProducts")
    public Result createProducts(@Valid @RequestBody Product product, BindingResult bindingResult) {
        log.info("=====================================创建商品======================================================");

        if (bindingResult.hasErrors()) {
            // 取第一个错误消息，或拼接所有
            String errorMessage = bindingResult.getFieldErrors().stream()
                    .map(error -> error.getField() + ": " + error.getDefaultMessage())
                    .findFirst()
                    .orElse("参数校验失败");

            return Result.error(errorMessage);
        }

        try {
            String result = productService.createProducts(product);
            return Result.success(result);
        } catch (Exception e) {
            log.error("创建商品失败", e);
            return Result.error("服务器内部错误: " + e.getMessage());
        }
    }


    /**
     * 修改商品
     *
     * @param product
     * @return
     */
    @PostMapping("/api/insertProducts")
    public Result insertProducts(@Valid @RequestBody Product product, BindingResult bindingResult) {
        log.info("=====================================修改商品======================================================");
        if (product.getId() == null) {
            return Result.error("商品ID不能为空");
        }

        if (bindingResult.hasErrors()) {
            // 取第一个错误消息，或拼接所有
            String errorMessage = bindingResult.getFieldErrors().stream()
                    .map(error -> error.getField() + ": " + error.getDefaultMessage())
                    .findFirst()
                    .orElse("参数校验失败");

            return Result.error(errorMessage);
        }

        try {

            Boolean success = productService.updateProducts(product);
            if (success) {
                return Result.success("更新成功");
            }else {
                return Result.error("<UNK>");
            }



        } catch (Exception e) {
            log.error("创建商品失败", e);
            return Result.error("服务器内部错误: " + e.getMessage());
        }
    }


    /**
     * 获取商品表的信息
     */
    @PostMapping("/api/metadata")
    public Result getTableStructure(HttpServletRequest request) {
        log.info("==============================获取表结结构信息================================");

        String token = request.getHeader("token");
        Claims claims = JwtUtils.parseJwt(token);
        String wxName = (String) claims.get("wxName");
        if ("admin".equals(wxName)) {
            try {
                TableStructureResponse columns = productService.getTableStructure("products");
                log.info("表结构信息获取成功:{}", columns);
                return Result.success(columns);
            } catch (Exception e) {
                log.error("获取表结构信息失败", e);
                return Result.error(e.getMessage());
            }
        } else {
            return Result.success("您没有操作权限");
        }
    }

    //  获取/添加 系列表
    @PostMapping("/api/classify")
    public Result getClassify(@RequestBody ClassifyRequest request) {
        try {
            Result classify = productService.getClassify(request);
            return classify;
        } catch (Exception e) {
            log.error("获取表结构信息失败", e);
            return Result.error(e.getMessage());
        }
    }
}
